import { ref } from 'vue'
import { ObjectType, addGlobalUncaughtErrorHandler, start } from 'qiankun'
import { QiankunFrame } from '@lhy-assist/qiankun'
import { PlatformAppRegistryConfig, qiankunFrame } from '@/qiankun/frame/frame'
import { globalErrorHandler } from '@/qiankun/error-handler'

let hasRegistry = false
const loadingApp = ref(false)

/**
 * 注册qiankun微应用
 * @param appConfigs
 * @param container
 */
function registryApps<T extends ObjectType>(appConfigs: PlatformAppRegistryConfig[], container: HTMLElement) {
  if (!hasRegistry) {
    hasRegistry = true

    QiankunFrame.registryApps(
      appConfigs,
      { container, frame: qiankunFrame as QiankunFrame<any, any> },
      {
        beforeLoad: async app => {
          loadingApp.value = true
        },
        afterMount: async app => {
          loadingApp.value = false
        },
        beforeUnmount: async app => {},
      }
    )
    addGlobalUncaughtErrorHandler(globalErrorHandler)
  }
}

function goRouter(url: string) {
  window.history.pushState(
    {
      current: url,
    },
    '',
    url
  )
}

/**
 * qiankun服务
 */
export function useQiankun() {
  return {
    loadingApp,
    registryApps,
    goRouter,
    qiankunFrame,
    start,
    destroy: () => {},
  }
}
